import pyttsx3
import io
import re
import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

# Python 3.x引入http.client模块。
import http.client
# Python 3.x引入urllib.parse模块。
import urllib.parse
import json
def processGETRequest(appKey, token, text, audioSaveFile, format, sampleRate) :
    host = 'nls-gateway-cn-shanghai.aliyuncs.com'
    url = 'https://' + host + '/stream/v1/tts'
    # 设置URL请求参数
    url = url + '?appkey=' + appKey
    url = url + '&token=' + token
    url = url + '&text=' + text
    url = url + '&format=' + format
    url = url + '&sample_rate=' + str(sampleRate)
    # voice 发音人，可选，默认是xiaoyun。
    # url = url + '&voice=' + 'xiaoyun'
    # volume 音量，范围是0~100，可选，默认50。
    # url = url + '&volume=' + str(50)
    # speech_rate 语速，范围是-500~500，可选，默认是0。
    url = url + '&speech_rate=' + str(50)
    # pitch_rate 语调，范围是-500~500，可选，默认是0。
    # url = url + '&pitch_rate=' + str(0)
    print(url)
    # Python 2.x请使用httplib。
    # conn = httplib.HTTPSConnection(host)
    # Python 3.x请使用http.client。
    conn = http.client.HTTPSConnection(host)
    conn.request(method='GET', url=url)
    # 处理服务端返回的响应。
    response = conn.getresponse()
    print('Response status and response reason:')
    print(response.status ,response.reason)
    contentType = response.getheader('Content-Type')
    print(contentType)
    body = response.read()
    if 'audio/mpeg' == contentType :
        with open(audioSaveFile, mode='wb') as f:
            f.write(body)
        print('The GET request succeed!')
    else :
        print('The GET request failed: ' + str(body))
    conn.close()
def processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate) :
    host = 'nls-gateway-cn-shanghai.aliyuncs.com'
    url = 'https://' + host + '/stream/v1/tts'
    # 设置HTTPS Headers。
    httpHeaders = {
        'Content-Type': 'application/json'
        }
    # 设置HTTPS Body。
    body = {'appkey': appKey, 'token': token, 'text': text, 'format': format, 'sample_rate': sampleRate}
    body = json.dumps(body)
    print('The POST request body content: ' + body)
    # Python 2.x请使用httplib。
    # conn = httplib.HTTPSConnection(host)
    # Python 3.x请使用http.client。
    conn = http.client.HTTPSConnection(host)
    conn.request(method='POST', url=url, body=body, headers=httpHeaders)
    # 处理服务端返回的响应。
    response = conn.getresponse()
    print('Response status and response reason:')
    print(response.status ,response.reason)
    contentType = response.getheader('Content-Type')
    print(contentType)
    body = response.read()
    if 'audio/mpeg' == contentType :
        with open(audioSaveFile, mode='wb') as f:
            f.write(body)
        print('The POST request succeed!')
    else :
        print('The POST request failed: ' + str(body))
    conn.close()


def audio(textUrlencode,audioSaveFile):
    # 采用RFC 3986规范进行urlencode编码。
    # Python 2.x请使用urllib.quote。
    # textUrlencode = urllib.quote(textUrlencode, '')
    # Python 3.x请使用urllib.parse.quote_plus。
    textUrlencode = urllib.parse.quote_plus(textUrlencode)
    textUrlencode = textUrlencode.replace("+", "%20")
    textUrlencode = textUrlencode.replace("*", "%2A")
    textUrlencode = textUrlencode.replace("%7E", "~")
    print('text: ' + textUrlencode)
    format = 'wav'
    sampleRate = 16000
    # GET请求方式
    processGETRequest(APPKEY, TOKEN, textUrlencode, audioSaveFile, format, sampleRate)
    # POST请求方式
    # processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate)




URL = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1"
# TOKEN = "175229e3c9ad4bcb994c722cd7b89c2f"  # 参考https://help.aliyun.com/document_detail/450255.html获取token
# APPKEY = "qoJMhXQVMj1ZdxrY"  # 获取Appkey请前往控制台：https://nls-portal.console.aliyun.com/applist 翠姐
APPKEY = "SDjNIercuz3hExOL"  # 获取Appkey请前往控制台：https://nls-portal.console.aliyun.com/applist 暖男

client = AcsClient(
    "LTAI5tDUPZfPbT2AvUdWKGQV",
    "8o3FmXvpRcaxzMWUZbzn1lD1t06DPa",
    "cn-shanghai"
);


def get_token():
    # 创建request，并设置参数。
    request = CommonRequest()
    request.set_method('POST')
    request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
    request.set_version('2019-02-28')
    request.set_action_name('CreateToken')

    try:
        response = client.do_action_with_exception(request)
        print(response)

        jss = json.loads(response)
        if 'Token' in jss and 'Id' in jss['Token']:
            token = jss['Token']['Id']
            expireTime = jss['Token']['ExpireTime']
            print("token = " + token)
            print("expireTime = " + str(expireTime))
            return token
    except Exception as e:
        print(e)


# 以下代码会根据上述TEXT文本反复进行语音合成



TOKEN = get_token()



def read_srt_file(srt_file_path):
    with io.open(srt_file_path, "r", encoding="utf-8") as file:
        srt_text = file.read()

    # 使用正则表达式匹配 SRT 文件中的文本和时间信息
    pattern = re.compile(r"(\d+):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+)")
    lines = re.split(r'\n\d+\n', srt_text)
    time_infos = pattern.findall(srt_text)

    return lines, time_infos


def text_to_speech(text, output_file):
    engine = pyttsx3.init()
    engine.save_to_file(text, output_file)
    engine.runAndWait()


def format_time_to_ms(time_info):
    h1, m1, s1, ms1, h2, m2, s2, ms2 = time_info
    start_time_ms = int(h1) * 3600000 + int(m1) * 60000 + int(s1) * 1000 + int(ms1)
    end_time_ms = int(h2) * 3600000 + int(m2) * 60000 + int(s2) * 1000 + int(ms2)
    return start_time_ms, end_time_ms


def extract_text_from_srt(srt_line):
    # 使用正则表达式匹配 SRT 文件中的时间信息和文本
    pattern = re.compile(r"(\d+):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+)\n(.+)")
    matches = pattern.findall(srt_line)
    extracted_text = ""
    for match in matches:
        extracted_text += match[8] + " "
    return extracted_text


def extract_filename(file_path):
    file_name = os.path.basename(file_path)
    return file_name.split('.')[0]


def is_text_empty(text):
    if text.strip() == "":
        return True
    else:
        return False


def text_to_audio(srt_file_path):
    lines, time_infos = read_srt_file(srt_file_path)
    for i, line in enumerate(lines):
        if line.strip():  # 跳过空行
            start_time_ms, end_time_ms = format_time_to_ms(time_infos[i])
            output_file = f"{start_time_ms}-{end_time_ms}.wav"
            print(output_file)
            text_from_srt = extract_text_from_srt(line)
            print(text_from_srt, len(text_from_srt))
            output_file = 'buff/5_wav/' + extract_filename(srt_file_path) + '/' + output_file
            if text_from_srt.strip():
                audio(text_from_srt, output_file)
                print('wav->',text_from_srt,'->',output_file)

def delete_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)
        print(f"文件 {file_path} 已成功删除")
    else:
        print(f"文件 {file_path} 不存在")


def deal_6_srt_to_audio(srtDirs):
    for root, dirs, files in os.walk(srtDirs):
        for file in files:
            # 获取文件的完整路径
            srt_file_path = os.path.join(root, file)

            # 获取文件的相对路径
            video_relative_path = os.path.relpath(srt_file_path, srtDirs)

            # 使用split()函数拆分相对路径，并将文件名的部分用下划线连接
            parts = video_relative_path.split(os.path.sep)
            formatted_name = '_'.join(parts)
            filename_without_ext = os.path.splitext(formatted_name)[0]
            # 打印格式化后的文件名
            # print(formatted_name)
            # print(filename_without_ext)
            if filename_without_ext == '.DS_Store':
                continue;
            text_to_audio(srt_file_path)


deal_6_srt_to_audio("buff/4_ctr_wav/")
